<?php

namespace App\Models;

use App\Common\Tools;
use App\Models\Channel;
use App\Models\HdpChannel;
use App\Models\LiveProgram;
use Cache;
use Log;

class VoiceSearchChannel
{
    public function search($text, $matches)
    {
        $keyword = trim($matches[2]);
        $keyword = str_replace(['频道'], '', $keyword);
        $channelObjs = Channel::where("name", $keyword)->limit(10)->get();
        if ($channelObjs && count($channelObjs) > 0) {
            $channels = [];
            foreach ($channelObjs as $key => $channelObj) {
                $channels[$key] = [
                    'model' => 'channel',
                    'name' => $channelObj->name,
                    'code' => $channelObj->code,
                    'logo' => $channelObj->logo,
                    'tags' => $channelObj->tags,
                    'hot' => $channelObj->hot,
                    'targetActions' => $this->getTargetActionObjsByChannelCode($channelObj->code),
                    'liveProgram' => $this->getLiveProgramByChannelCode($channelObj->code)
                ];
            }
            return [
                'status' => 0,
                'message' => '',
                'datas' => $channels
            ];
        } else {
            return [
                'status' => 1002,
                'message' => '没有找到你想要的结果!',
            ];
        }
    }

    protected function getTargetActionObjsByChannelCode($channel_code)
    {
        $key = 'ChannelTargetActions_' . $channel_code;
        if (Cache::has($key)) {
            return Cache::get($key);
        } else {
            $targetActions = [];
            $targetActionObjs = HdpChannel::where("channel_code", $channel_code)->get();
            if ($targetActionObjs) {
                foreach ($targetActionObjs as $targetActionObj) {
                    array_push($targetActions, $targetActionObj->format2AI());
                }
            }
            Cache::put($key, $targetActions);
            return $targetActions;
        }
    }

    protected function getLiveProgramByChannelCode($channel_code)
    {
        $liveProgram = LiveProgram::where('channel_code', $channel_code)->first();
        if ($liveProgram) {
            return [
                "name" => $liveProgram->program_name,
                "start_time" => date("Y-m-d H:i:s", $liveProgram->start_time),
                "end_time" => date("Y-m-d H:i:s", $liveProgram->end_time),
                "wiki_id" => $liveProgram->wiki_id,
                "wiki_title" => $liveProgram->wiki_title,
                "wiki_cover" => Tools::getWikiCover($liveProgram->wiki_cover),
                "next_name" => "",
                "next_wiki_id" => ""
            ];
        } else {
            return null;
        }
    }
}
